/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.psp.service.impl;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.cspimp.psp.domain.TrainMember;
import me.zhengjie.modules.cspimp.psp.domain.TrainPlan;
import me.zhengjie.modules.cspimp.psp.domain.vo.TrainPlanVo;
import me.zhengjie.modules.cspimp.psp.repository.TrainMemberRepository;
import me.zhengjie.modules.cspimp.psp.service.dto.TrainMemberDto;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.psp.repository.TrainPlanRepository;
import me.zhengjie.modules.cspimp.psp.service.TrainPlanService;
import me.zhengjie.modules.cspimp.psp.service.dto.TrainPlanDto;
import me.zhengjie.modules.cspimp.psp.service.dto.TrainPlanQueryCriteria;
import me.zhengjie.modules.cspimp.psp.service.mapstruct.TrainPlanMapper;
import org.apache.commons.collections4.list.TransformedList;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zmm
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-30
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TrainPlanServiceImpl implements TrainPlanService {

    private final TrainPlanRepository trainPlanRepository;
    private final TrainPlanMapper trainPlanMapper;
    private final TrainMemberRepository trainMemberRepository;
    private final UserRepository userRepository;

    @Override
    public Map<String, Object> queryAll(TrainPlanQueryCriteria criteria, Pageable pageable) {
        List<TrainPlan> trainPlans = trainPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<TrainPlanDto> trainPlanList = new ArrayList<>();
        for (TrainPlan trainPlan : trainPlans) {
            TrainPlanDto trainPlanDto = new TrainPlanDto();
            BeanUtils.copyProperties(trainPlan, trainPlanDto);
            List<TrainMember> trainMemberList = trainMemberRepository.findByTrainPlanId(trainPlan.getId());
            List<TrainMemberDto> trainMemberDtoList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(trainMemberList)) {
                for (TrainMember trainMember : trainMemberList) {
                    User user = userRepository.findById(trainMember.getUserId()).get();
                    TrainMemberDto trainMemberDto = new TrainMemberDto();
                    BeanUtils.copyProperties(trainMember, trainMemberDto);
                    if (null != user) {
                        trainMemberDto.setUsername(user.getUsername());
                    }
                    trainMemberDtoList.add(trainMemberDto);
                }
            }
            trainPlanDto.setTrainMemberList(trainMemberDtoList);
            trainPlanList.add(trainPlanDto);
        }
        return PageUtil.toPage(PageUtil.listPage(trainPlanList, pageable));
    }

    @Override
    public List<TrainPlanDto> queryAll(TrainPlanQueryCriteria criteria) {


        return trainPlanMapper.toDto(trainPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public TrainPlanDto findById(Long id) {
        TrainPlan trainPlan = trainPlanRepository.findById(id).orElseGet(TrainPlan::new);
        ValidationUtil.isNull(trainPlan.getId(), "TrainPlan", "id", id);
        TrainPlanDto trainPlanDto = new TrainPlanDto();
        BeanUtils.copyProperties(trainPlan, trainPlanDto);
        List<TrainMember> trainMemberList = trainMemberRepository.findByTrainPlanId(trainPlan.getId());
        List<TrainMemberDto> trainMemberDtoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(trainMemberList)) {
            for (TrainMember trainMember : trainMemberList) {
                User user = userRepository.findById(trainMember.getUserId()).get();
                TrainMemberDto trainMemberDto = new TrainMemberDto();
                BeanUtils.copyProperties(trainMember, trainMemberDto);
                if (null != user) {
                    trainMemberDto.setUsername(user.getUsername());
                }
                trainMemberDtoList.add(trainMemberDto);
            }
        }
        trainPlanDto.setTrainMemberList(trainMemberDtoList);

        return trainPlanDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TrainPlanDto create(TrainPlanVo resources) {
        Set<Long> tranMemberUserIds = resources.getTrainMemberIds();
        if (CollectionUtils.isEmpty(tranMemberUserIds)) {
            throw new BadRequestException("培训人员不能为空");
        }
        String trainDateStr = resources.getTrainDate();
        TrainPlan trainPlan = new TrainPlan();
        BeanUtils.copyProperties(resources, trainPlan);
        trainPlan.setCid(0L);
        trainPlan.setTrainDate(trainDateStr);
        trainPlanRepository.save(trainPlan);
        //新增培训人员
        for (Long userId : tranMemberUserIds) {
            TrainMember trainMember = new TrainMember();
            trainMember.setTrainPlanId(trainPlan.getId());
            trainMember.setUserId(userId);
            trainMemberRepository.save(trainMember);
        }

        return trainPlanMapper.toDto(trainPlan);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TrainPlanVo resources) {
        TrainPlan trainPlan = trainPlanRepository.findById(resources.getId()).orElseGet(TrainPlan::new);
        ValidationUtil.isNull(trainPlan.getId(), "TrainPlan", "id", resources.getId());

        BeanUtils.copyProperties(resources, trainPlan);

        trainPlanRepository.save(trainPlan);
        //先删除之前的人员
        trainMemberRepository.deleteByTrainPlanId(trainPlan.getId());
        if (!CollectionUtils.isEmpty(resources.getTrainMemberIds())) {
            for (Long userId : resources.getTrainMemberIds()) {
                TrainMember trainMember = new TrainMember();
                trainMember.setTrainPlanId(trainPlan.getId());
                trainMember.setUserId(userId);
                trainMemberRepository.save(trainMember);
            }
        }


    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            trainPlanRepository.deleteById(id);

//            trainMemberRepository.deleteByTrainPlanId(id);
        }
    }

    @Override
    public void download(List<TrainPlanDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TrainPlanDto trainPlan : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("创建时间", trainPlan.getCreateTime());
            map.put("更新时间", trainPlan.getUpdateTime());
            map.put("创建者", trainPlan.getCreateBy());
            map.put("更新者", trainPlan.getUpdatedBy());
            map.put("培训标题", trainPlan.getTitle());
            map.put("培训内容", trainPlan.getContent());
            map.put("讲师", trainPlan.getLecturer());
            map.put("培训地点", trainPlan.getPlace());
            map.put("培训日期", trainPlan.getTrainDate());
            map.put("培训时长", trainPlan.getTrainTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}